<template>
  <div>
    <AduitModal />
    <a-table bordered :data-source="dataSource" :columns="columns" ellipsis=true>
      <template #role="{ text: role }">
        <span>
          <a-tag :color="RoleNumToTextMap[role].color">
            {{ RoleNumToTextMap[role].text }}
          </a-tag>
        </span>
      </template>
      <template #address="{ text: addressList }">
        <span>{{ addressList[0].detail }}</span>
      </template>
      <template #operation="{ record }">
        <template v-if="getStorageRole() === 3 && record.role === 3">
          <a-popconfirm v-if="dataSource.length" title="确定要删掉吗?" ok-text="是" cancel-text="否"
            @confirm="onDelete(record.id)">
            <a-button type="link">删除</a-button>
          </a-popconfirm>
        </template>
        <template v-else>
          <a-tooltip title="您没有权限删除该用户">
            <a-button type="text" disabled>删除</a-button>
          </a-tooltip>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script>
import { defineComponent, ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';

import { getUserList, deleteSuperAdmin } from '../../service/api/user';
import { getStorageRole } from '../../utils/index';
import { RoleNumToTextMap } from './const';
import AduitModal from './AduitModal.vue';

const dataSource = ref([]);
const columns = [
  {
    title: '用户 id',
    dataIndex: 'id',
  },
  {
    title: '用户名',
    width: 80,
    dataIndex: 'username',
  },
  {
    title: '用户角色',
    dataIndex: 'role',
    slots: {
      customRender: 'role',
    },
  },
  {
    title: '默认地址',
    dataIndex: 'address',
    minWidth: 200,
    slots: {
      customRender: 'address',
    },
  },
  {
    title: '所在店铺 id',
    dataIndex: 'shop_id',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: "center",
    width: 100,
    slots: {
      customRender: 'operation',
    },
  },
];

const useHttpRequestEffect = () => {
  const getUserListRequest = async () => {
    const res = await getUserList();
    dataSource.value = res?.data;
  }
  const deleteSuperAdminRequest = async (id) => {
    const res = await deleteSuperAdmin(id);
    if (res?.data?.res) {
      message.success("删除成功")
    } else {
      message.error("删除失败")
    }
  }
  return { getUserListRequest, deleteSuperAdminRequest }
}

export default defineComponent({
  components: {
    AduitModal
  },

  setup() {
    const { getUserListRequest, deleteSuperAdminRequest } = useHttpRequestEffect();
    const onDelete = id => {
      dataSource.value = dataSource.value.filter(item => item.id !== id);
      deleteSuperAdminRequest(id);
    };

    onMounted(async () => {
      await getUserListRequest();
    });

    return {
      columns,
      dataSource,
      RoleNumToTextMap,
      getStorageRole,
      onDelete,
    };
  },
});
</script>

<style lang="less">

</style>